// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GraphSLAMModelAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Navigation.Visualization
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using Microsoft.Robotics.Navigation;
    using Microsoft.Robotics.Navigation.Runtime;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Numerics.GraphOptimization;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Vision;
    using Microsoft.Robotics.Visualization;

    /// <summary>
    /// Model agent that receives a GraphSLAMMessage and publishes a GraphSLAMModel
    /// </summary>
    [DataContract]
    public sealed class GraphSLAMModelAgent : ModelAgent<GraphMessage, GraphSLAMModel>
    {
        /// <summary>
        /// Initializes a new instance of the GraphSLAMModelAgent class
        /// </summary>
        /// <param name="name">name of the agent instance</param>
        /// <param name="producer">producer of GraphSLAMMessages</param>
        /// <param name="maxUpdateIntervalMilliseconds">interval at which to update the UI</param>
        public GraphSLAMModelAgent(
            string name,
            IProducer<GraphMessage> producer,
            int maxUpdateIntervalMilliseconds) 
            : base(name, producer.Name, maxUpdateIntervalMilliseconds)
        {
        }

        /// <summary>
        /// Called on initialization of GraphSLAMModelAgent
        /// </summary>
        /// <param name="locator">Agent Locator</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
        }

        /// <summary>
        /// Updates the model
        /// </summary>
        /// <param name="state">The GraphSLAMMessage</param>
        /// <returns>true if the model was updated, false otherwise</returns>
        protected override bool UpdateModel(GraphMessage state)
        {
            Pose2D center = new Pose2D(0, 0, 0);
            double scale = this.GetScale(state.Nodes, ref center);

            ImageFrameRgb image = new ImageFrameRgb(550, 550);
            this.DrawEdge(image, state.Nodes, state.Edges, scale, center);
            this.Model.VideoFrame = new VideoFrame()
            {
                Data = image.ImageData,
                Size = new System.Drawing.Size(550, 550),
                Format = SimplePixelFormat.Rgb24,
                Stride = image.Width * image.BytesPerPixel
            };

            return true;
        }

        /// <summary>
        /// Gets the isotropic scale factor so that the graph fits inside the window
        /// </summary>
        /// <param name="nodes">List of nodes</param>
        /// <param name="center">center of graph</param>
        /// <returns>isotropic scale factor</returns>
        private double GetScale(List<Pose2D> nodes, ref Pose2D center)
        {
            double min_x = double.MaxValue;
            double min_y = double.MaxValue;
            double max_x = double.MinValue;
            double max_y = double.MinValue;
            center.X = 0;
            center.Y = 0;

            for (int i = 0; i < nodes.Count; i++)
            {
                center.X += nodes[i].X;
                center.Y += nodes[i].Y;

                if (nodes[i].X < min_x)
                {
                    min_x = nodes[i].X;
                }

                if (nodes[i].Y < min_y)
                {
                    min_y = nodes[i].Y;
                }

                if (nodes[i].X > max_x)
                {
                    max_x = nodes[i].X;
                }

                if (nodes[i].Y > max_y)
                {
                    max_y = nodes[i].Y;
                }
            }

            center.X /= nodes.Count;
            center.Y /= nodes.Count;

            if (max_x - min_x > max_y - min_y)
            {
                return 450.0 / (max_x - min_x);
            }
            else
            {
                return 450.0 / (max_y - min_y);
            }
        }

        /// <summary>
        /// Draw edges on the image
        /// </summary>
        /// <param name="image">Image to draw on</param>
        /// <param name="nodes">List of nodes</param>
        /// <param name="edges">List of edges</param>
        /// <param name="scale">isotropic scale</param>
        /// <param name="center">center of the graph</param>
        private void DrawEdge(ImageFrameRgb image, List<Pose2D> nodes, List<Pose2DEdge> edges, double scale, Pose2D center)
        {
            for (int i = 0; i < edges.Count; i++)
            {
                if (edges[i].IndexI >= 0 && edges[i].IndexI < nodes.Count && edges[i].IndexJ >= 0 && edges[i].IndexJ < nodes.Count)
                {
                    Pose2D point1 = (nodes[edges[i].IndexI] - center) * scale;
                    point1 += new Pose2D(250, 250, 0);
                    point1.X = 500 - point1.X;

                    Pose2D point2 = (nodes[edges[i].IndexJ] - center) * scale;
                    point2 += new Pose2D(250, 250, 0);
                    point2.X = 500 - point2.X;

                    if (point1.X >= 0 && point1.X < image.Width && point1.Y >= 0 && point1.Y < image.Height
                        && point2.X >= 0 && point2.X < image.Width && point2.Y >= 0 && point2.Y < image.Height)
                    {
                        if (i == 0)
                        {
                            ImageOperations2D.DrawHollowCircle(image, 5, point1.X, point1.Y, new RgbPix(255, 0, 0));
                        }

                        if (i == edges.Count - 1)
                        {
                            ImageOperations2D.DrawHollowCircle(image, 5, point2.X, point2.Y, new RgbPix(255, 255, 0));
                        }

                        if (Math.Abs(edges[i].IndexI - edges[i].IndexJ) > 1)
                        {
                            ImageOperations2D.DrawLine(image, new Point2D<int>((int)point1.X, (int)point1.Y), new Point2D<int>((int)point2.X, (int)point2.Y), new RgbPix(255, 0, 0));
                        }
                        else
                        {
                            ImageOperations2D.DrawLine(image, new Point2D<int>((int)point1.X, (int)point1.Y), new Point2D<int>((int)point2.X, (int)point2.Y), new RgbPix(0, 255, 0));
                        }
                    }
                }
                else
                {
                    throw new Exception(
                        "An edge has a constraint between two nodes, one or both of which may not exist in the graph." +
                        " Index I " + edges[i].IndexI + 
                        " Index J " + edges[i].IndexJ +
                        " Nodes in graph " + nodes.Count);
                }
            }
        }
    }
}
